<?php

class SuppliersController extends AppController {

    var $name = 'Suppliers';
    var $pageTitle = 'Vendor Information';
    var $viewPath = 'its/admins/suppliers';
    var $uses = array('Supplier', 'Brand', 'CustomerSupplier', 'Customer', 'Province');
    var $paginate = array('order' => 'Supplier.code DESC');

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_admins');
        $this->set('tabMenu', 'tabmenus/its/admins');
    }

    function display() {
        parent::display();
        $this->_paging(Inflector::classify($this->name), 'LIKE');
    }

    function save() {
        $supplier_id = null;
        if (!empty($this->data)) {
            $this->data['Supplier']['code'] = strtoupper($this->data['Supplier']['code']);
            $this->data['Supplier']['collector_id'] = $this->Session->read('Auth.User.id');
            if ($this->Supplier->save($this->data)) {
                $this->Session->setFlash("Supplier {$this->data['Supplier']['code']} save succesfull.", 'flash/ok');
                $supplier_id = $this->Supplier->id;
            } else {
                $this->Session->setFlash("Supplier save fail.", 'flash/fail');
                // ถ้าเป็น mode edit เก็บ id เอาไว้กรณีบันทึกข้อมูลผิด
                $supplier_id = $this->data['Supplier']['id'];
            }
        }
        $this->setAction('view', $supplier_id);
    }

    function view($id = null) {
        // edit
        if ($id != null) {
            $this->data = $this->Supplier->findById($id);
            $this->Supplier->id = $id;
            $this->set('neighbors', $this->Supplier->find('neighbors', array('fields' => array('id', 'name'))));
            $this->set('mode', 'edit');
        } else {
            $this->set('mode', 'add');
        }
        $this->set('provinces', $this->Province->find('list'));
    }

    function delete($id = null) {
        $is_success = false;

        // ถ้ายังไม่มี Brand ไหน ใช้ Supplier นี้ ลบได้
        if (!$this->Brand->hasAny(array('supplier_id' => $id))) {
            $is_success = $this->Supplier->delete($id);
        }

        if ($is_success) {
            $this->Session->setFlash("Suplplier delete succesfull.", 'flash/ok');
            $this->setAction('display');
        } else {
            $this->Session->setFlash("Can not delete this supplier.", 'flash/fail');
            $this->setAction('view', $id);
        }
    }

    /**
     * action สำหรับ แสดง Customer Contract list
     * @param int $supplier_id
     */
    function display_customer($supplier_id) {
        $this->layout = 'ajax';
        $this->CustomerSupplier->contain('Customer');

        $this->data = $this->CustomerSupplier->findAllBySupplierId($supplier_id);
        $this->set('supplier_id', $supplier_id);
    }

    function view_customer($supplier_id, $cust_sup_id = null) {
        $this->layout = 'ajax';

        if (!empty($cust_sup_id)) {
            $this->CustomerSupplier->contain();
            $this->data = $this->CustomerSupplier->findById($cust_sup_id);
        } else {

            // Subquery ดึงรายการ Customer ที่ไม่อยู่ใน Customer Contract list ของ Supplier นี้
            $conditionsSubQuery['CustomerSupplier.supplier_id'] = $supplier_id;
            $dbo = $this->CustomerSupplier->getDataSource();
            $subQuery = $dbo->buildStatement(
                            array(
                        'fields' => array('CustomerSupplier.customer_id'),
                        'table' => $dbo->fullTableName($this->CustomerSupplier),
                        'alias' => 'CustomerSupplier',
                        'conditions' => $conditionsSubQuery,
                        'order' => null,
                        'limit' => null,
                        'group' => null,
                            ), $this->CustomerSupplier
            );
            $subQuery = ' Customer.id NOT IN (' . $subQuery . ') ';
            $subQueryExpression = $dbo->expression($subQuery);
            $conditions[] = $subQueryExpression;
            $this->data = null;
        }

        $customers = $this->Customer->find('list', compact('conditions'));
        $this->set('customers', $customers);
        $this->set('supplier_id', $supplier_id);
    }

    /**
     * บันทึก Customer เข้าไปใน Contract list ของ Supplier
     */
    function save_customer() {
        $this->layout = 'ajax';
        $supplier_id = $this->data['CustomerSupplier']['supplier_id'];

        $this->CustomerSupplier->query("BEGIN");
        ;
        $this->data['CustomerSupplier']['collector_id'] = $this->Auth->user('id');
        if ($this->CustomerSupplier->save($this->data)) {

            $this->Supplier->id = $supplier_id;

            // update supplier has cust inventory
            if ($this->CustomerSupplier->hasAny(array('supplier_id' => $supplier_id, 'has_cust_inventory'))) {
                $this->Supplier->saveField('has_cust_inventory', true);
            } else {
                $this->Supplier->saveField('has_cust_inventory', false);
            }

            // update supplier has supplier inventory
            if ($this->CustomerSupplier->hasAny(array('supplier_id' => $supplier_id, 'has_supplier_inventory'))) {
                $this->Supplier->saveField('has_supplier_inventory', true);
            } else {
                $this->Supplier->saveField('has_supplier_inventory', false);
            }
            $this->CustomerSupplier->query("COMMIT");
            ;
            $this->Session->setFlash("Add Customer to contract list succesfull.", 'flash/ok');
        } else {
            $this->CustomerSupplier->query("ROLLBACK");
            $this->Session->setFlash("Cannot add customer to contract list.", 'flash/fail');
        }
        $this->setAction('view', $supplier_id);
    }

    /**
     * ลบ Customer ออกจาก Contract List ของ Supplier
     * @param <type> $id
     */
    function delete_customer($id) {
        $this->layout = 'ajax';
        $is_success = false;

        // ลบ รายการ
        $this->CustomerSupplier->id = $id;
        $supplier_id = $this->CustomerSupplier->field('supplier_id');
        $is_success = $this->CustomerSupplier->delete($id);

        if ($is_success) {
            $this->Session->setFlash("Delete customer from contract list succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this customer.", 'flash/fail');
        }
        $this->setAction('display_customer', $supplier_id);
    }

    function inplace_editor($field, $id) {
        parent::inplace_editor($this->Supplier, $field, $id);
    }

}

?>
